package com.tsugun.mediaplayer.presenter.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.RectF
import android.media.MediaMetadataRetriever
import android.util.Log

import com.tsugun.mediaplayer.view.loader.MediaImageLoad

import java.net.HttpURLConnection
import java.net.URL

/**
 * bitmap裁剪工具
 * Created by shize on 2017/3/27.
 */

object BitmapHelper {
    /**
     * 裁剪模式
     */
    val MODE_FILLET = 0x10 // 裁剪图片大小的圆角矩形图片
    val MODE_CIRCLE = 0x30 // 裁剪圆形图片
    val MODE_FILLET_SQUARE = 0x20 // 裁剪圆角方形图片

    /**
     * 裁剪bitmap为方形圆角bitmap

     * @param bitmap       Bitmap root
     * *
     * @param filletRadius Fillet radius
     * *
     * @param scissorMode  One of [.MODE_FILLET],[.MODE_FILLET_SQUARE],
     * *                     [.MODE_CIRCLE]
     * *
     * @return bitmap
     */
    @Synchronized fun scissorBitmap(bitmap: Bitmap, filletRadius: Float, scissorMode: Int): Bitmap {
        var filletRadius = filletRadius
        val rectF: RectF
        // 根据图片的长宽获取适合的尺寸
        val length = Math.min(bitmap.width, bitmap.height)
        when (scissorMode) {
            MODE_FILLET -> rectF = RectF(0f, 0f, bitmap.width.toFloat(), bitmap.height.toFloat())
            MODE_CIRCLE -> {
                filletRadius = (length / 2).toFloat()
                rectF = RectF(0f, 0f, length.toFloat(), length.toFloat())
            }
            MODE_FILLET_SQUARE -> rectF = RectF(0f, 0f, length.toFloat(), length.toFloat())
            else -> return bitmap
        }
        return drawBitmap(bitmap, filletRadius, rectF)
    }

    /**
     * 绘制指定形状bitmap

     * @param bitmap       bitmap
     * *
     * @param filletRadius 圆角半径
     * *
     * @param rectF        基础矩形
     * *
     * @return bitmap
     */
    private fun drawBitmap(bitmap: Bitmap, filletRadius: Float, rectF: RectF): Bitmap {
        val width = bitmap.width
        val height = bitmap.height
        val rLength = rectF.right.toInt()
        val bLength = rectF.bottom.toInt()

        val src = Rect((width - rLength) / 2, height - bLength, (width + rLength) / 2, bLength)
        val dst = Rect(0, 0, rLength, bLength)

        val paint = Paint()
        paint.isAntiAlias = true // 抗锯齿
        paint.color = 0xff424242.toInt() // 颜色
        val output = Bitmap.createBitmap(rLength, bLength, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(output)
        canvas.drawARGB(0, 0, 0, 0)
        // 第一个参数为基础矩形，第二、三参数为圆角半径，最后为画笔
        canvas.drawRoundRect(rectF, filletRadius, filletRadius, paint)

        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN) // 相交模式
        canvas.drawBitmap(bitmap, src, dst, paint)
        return output
    }

    /**
     * 从媒体文件中提取bitmap

     * @param musicUrl 媒体文件地址
     * *
     * @return bitmap
     */
    fun getBitmapFromMedia(musicUrl: String): Bitmap? {
        var bitmap: Bitmap? = null
        val metadataRetriever = MediaMetadataRetriever()
        try {
            metadataRetriever.setDataSource(musicUrl)
            val artwork = metadataRetriever.embeddedPicture
            if (artwork != null) {
                val options = BitmapFactory.Options()
                options.inJustDecodeBounds = true
                bitmap = BitmapFactory.decodeByteArray(artwork, 0, artwork.size, options)
                options.inJustDecodeBounds = false
                options.inPreferredConfig = Bitmap.Config.RGB_565
                if (options.outHeight > MediaImageLoad.getCacheSize()) {
                    options.inSampleSize = options.outHeight / MediaImageLoad.getCacheSize()
                }
                bitmap = BitmapFactory.decodeByteArray(artwork, 0, artwork.size, options)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            metadataRetriever.release()
        }
        if (bitmap != null)
            Log.i(LogHelper.TAG, "getBitmapFromMedia: 找到了" + musicUrl + "的歌曲图片!")
        return bitmap
    }

    /**
     * 从网络获取bitmap

     * @param imageUrl 网址
     * *
     * @return bitmap
     */
    fun getBitmapFromNetwork(imageUrl: String): Bitmap? {
        var bitmap: Bitmap? = null
        try {
            val url = URL(imageUrl)
            val connection = url.openConnection() as HttpURLConnection
            bitmap = BitmapFactory.decodeStream(connection.inputStream)
            connection.disconnect()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return bitmap
    }

    /**
     * 按比例缩放bitmap图片

     * @param bitmap     原图
     * *
     * @param targetSize 目标尺寸
     * *
     * @return 缩放图
     */
    @Deprecated("")
    fun scaleBitmap(bitmap: Bitmap?, targetSize: Float): Bitmap? {
        if (bitmap == null) {
            return null
        }
        var ratio = 1f
        val height = bitmap.height
        val width = bitmap.width
        if (height > targetSize) {
            ratio = targetSize / height
        }
        val matrix = Matrix()
        matrix.preScale(ratio, ratio)
        val scaleBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false)
        if (scaleBitmap == bitmap) {
            return scaleBitmap
        }
        bitmap.recycle()
        return scaleBitmap
    }

    /**
     * 将图片缩放到指定大小

     * @param bitmap 图片
     * *
     * @param height 指定高度
     * *
     * @param width  指定宽度
     * *
     * @return 缩放后的图片
     */
    @Deprecated("")
    fun resizeImage(bitmap: Bitmap?, height: Int, width: Int): Bitmap? {
        if (bitmap == null) {
            return null
        }
        val bitmapHeight = bitmap.height
        val bitmapWidth = bitmap.width
        if (bitmap.height < height) {
            return bitmap
        }
        val scaleWidth = width.toFloat() / bitmapWidth
        val scaleHeight = height.toFloat() / bitmapHeight
        val matrix = Matrix()
        matrix.postScale(scaleWidth, scaleHeight)
        val resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false)
        if (resizeBitmap == bitmap) {
            return resizeBitmap
        }
        bitmap.recycle()
        return resizeBitmap
    }

    /**
     * 通过歌手名称从酷我上获取歌手图片
     */
    fun getArtistImageFromNet(artist: String): Bitmap? {
        val url = HttpJSONHelper.getImageURL(artist)
        return HttpJSONHelper.downloadBitmap(url!!)
    }
}
